import React, { PureComponent, Fragment } from 'react';

import { connect } from 'dva';
import router from 'umi/router';

import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Radio, Popconfirm } from 'antd';

import MyIcon from '@/components/MyIcon';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import StandardTableForm from '@/components/StandardTable/StandardTableForm';
import StandardTableHandle from '@/components/StandardTable/StandardTableHandle';

import { goods as columns } from '@/commons/columns';
import { goods as map } from '@/commons/map';

import GoodsAdd from './Modals/GoodsAdd'

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

const CreateForm = Form.create()(props => {
  const { type, queryRow, modalVisible, form, handleModalVisible } = props;

  return (
    <Modal
      destroyOnClose
      width={1300}
      visible={modalVisible}
      onCancel={handleModalVisible.bind(null, false)}
      footer={null}
      bodyStyle={{padding: 0}}
    >
      <GoodsAdd queryRow={queryRow} parentVisable={() => handleModalVisible(false)} />
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ goods, loading }) => ({
  goods,
  loading: loading.models.goods,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    queryRow: {},
  };

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: queryRow => (
      <Fragment>
        <Button
          icon="eye" 
          type="primary"
          size="small" 
          onClick={this.handlePage.bind(null, queryRow)}
          style={{marginBottom: 8}}
        >查看详情</Button>
        {
          queryRow.status !== 2 
          &&
          <Popconfirm 
            title="确认下架抽奖?" 
            okText="确认" 
            cancelText="取消"
            onConfirm={this.handleUpdate.bind(null, queryRow)} 
          >
            <Button 
              icon="arrow-down" 
              type="primary" 
              ghost 
              size="small"
            >下架抽奖</Button>
          </Popconfirm>          
        }
        <Button 
          icon="arrow-down" 
          type="primary" 
          ghost 
          size="small"
          onClick={this.handleModalVisible.bind(null, queryRow)}
          style={{marginTop: 8}}
        >编辑抽奖</Button>
      </Fragment>
    ),
  }];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'goods/fetch',
      payload:{type:'all'}
    });
  }

  handleToggleTable = e => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'goods/fetch',
      payload: { status: e.target.value }
    });
  }

  handlePage = (queryRow = {}, e) => {
    e.preventDefault();

    router.push({
      pathname: '/goods/center/profile',
      query: {
        id: queryRow.id
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'goods/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'goods/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch, goods } = this.props;
    const { selectedRows } = this.state;

    const typeObj = {}
    goods.type === '1' && Object.assign(typeObj, { type: 1 })

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'goods/remove',
          payload: { ...typeObj, id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'goods/fetch'
              });
              this.setState({
                selectedRows: []
              });
              message.success(goods.type === '1' ? `共有${data}条奖品从首页移除成功~` : `共有${data}条奖品从列表移除成功~`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        endAt: fieldsValue.endAt && fieldsValue.endAt.format('YYYY-MM-DD hh:mm'),
        createdAt: fieldsValue.createdAt && fieldsValue.createdAt.format('YYYY-MM-DD hh:mm'),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.format('YYYY-MM-DD hh:mm'),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'goods/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (queryRow = {}) => {
    const payload = {}

    if (isNaN(queryRow.id)) {
      Object.assign(payload, {
        modalVisible: false,
        queryRow: {}
      });
    } else {
      Object.assign(payload, {
        modalVisible: true,
        queryRow
      });
    }
    this.setState(state => ({
      ...state,
      ...payload
    }));
  };

  handleUpdate = (queryRow = {}) => {
    const { dispatch } = this.props;
    console.log(queryRow, 12)

    dispatch({
      type: 'goods/update',
      payload: { status: 2, id: queryRow.id },
      callback: ({ errno, data }) => {
        if (errno) {
          message.error('奖品下架失败！');
        } else {
          dispatch({
            type: 'goods/fetch'
          });
          message.success('奖品下架成功~');
        }
      }
    });

    // this.handleModalVisible();
  };

  render() {
    const {
      goods: { data, status },
      loading,
      form,
    } = this.props;
    const { queryRow, expandForm, selectedRows, modalVisible } = this.state;

    const parentMethods = {
      queryRow,
      modalVisible,
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <PageHeaderWrapper 
        title="抽奖中心" 
        action={moment().format('LLLL')}
      >
        <Card bordered={false}>
          <StandardTableForm
            expandForm={expandForm}
            data={map}
            form={form}
            onSubmit={this.handleSearch}
            onReset={this.handleFormReset}
            onToggle={this.toggleForm}
          />
          <StandardTableHandle
            status={status}
            selectedRows={selectedRows}
            radioGroups={
              {
                'all': <Fragment><MyIcon type="icon-all" />&nbsp;全部</Fragment>, 
                '0': <Fragment><MyIcon type="icon-ongoing" />&nbsp;进行中</Fragment>,
                '1': <Fragment><MyIcon type="icon-expired" />&nbsp;已结束</Fragment>,
                '2': <Fragment><MyIcon type="icon-ended" />&nbsp;已下架</Fragment>,
                // '3': <Fragment><MyIcon type="icon-offshelf" />&nbsp;已失效</Fragment>,
              }
            }
            menuItems={{'remove': <Button type="danger" icon="delete">删除</Button>}}
            action={
              <Fragment>
                {
                  status === '0' 
                  ?
                  <Button type="primary" icon="plus" onClick={this.handleModalVisible.bind(null, {id: 0})} style={{marginRight: 0}}>
                    新增
                  </Button>
                  :
                  null
                }
                {/*<a href="/favicon.png" target="_blank">
                  <Button type="primary" icon="download">EXCEL</Button>
                </a>*/}
              </Fragment>
            }
            onToggleTable={this.handleToggleTable}
            onMenuClick={this.handleMenuClick}
          />
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            bordered={true}
            scroll={{ x: 1300 }}
            columns={this.columns}
            expandedRowRender={record => (
              record.type === 1
              ?
              <Fragment>
                <section>关联小程序 ID：{record.appId}</section>
                <section>备注：{record.remark}</section>
              </Fragment>
              :
              null
            )}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <CreateForm {...parentMethods} />
      </PageHeaderWrapper>
    );
  }
}

export default TableList;